package com.cloudfun.campusshare.service.handler;

import com.cloudfun.campusshare.common.constant.DelayMsgType;
import com.cloudfun.campusshare.common.constant.OrderStatus;
import com.cloudfun.campusshare.entity.OrderEntity;
import com.cloudfun.campusshare.repo.OrderEntityRepo;
import com.cloudfun.campusshare.sender.DelayMessage;
import com.cloudfun.campusshare.service.DeviceOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/6/18 20:00
 * @description : 用户预约超时未扫码
 */
@Component
public class UserSubscribeExpireMessageHandler implements DelayMessageHandler {

    @Resource
    private OrderEntityRepo orderEntityRepo;

    @Autowired
    private DeviceOrderService deviceOrderService;

    @Override
    public DelayMsgType support() {
        return DelayMsgType.EXPIRE_USER_SUBSCRIBE;
    }

    @Override
    @Transactional
    public void handleMessage(DelayMessage message) {
        OrderEntity orderEntity = orderEntityRepo.findById(message.getOrderId()).get();
        //如果十分钟之后 用户没有扫码设备，则设置订单为过期状态
        if (OrderStatus.IN_ORDER.equals(orderEntity.getOrderStatus())) {
            orderEntity.setOrderStatus(OrderStatus.SUBSCRIBE_EXPIRE);
            orderEntityRepo.save(orderEntity);
            try{
                prepareUserContext(message);
                deviceOrderService.transferOrReleaseDeviceLock(message.getDeviceId());
            }finally {
                destroyUserContext();
            }
        }
    }
}
